<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller
{
	private $_food;
	private $_wood;
	private $_metal;
	private $_petroleum;
	function __construct()
	{
		parent::__construct();
		$this->_food = $this->config->item('food');
		$this->_wood = $this->config->item('wood');
		$this->_metal = $this->config->item('metal');
		$this->_petroleum = $this->config->item('petroleum');
		$this->load->library('Mydatetime');
		$this->load->library('session');
		$this->load->model('home/home_model');
	}
	
	public function index()
	{
	   if(!$this->session->userdata('username'))
       {
            redirect(site_url('login'));
            die();
       }
		$data = array();
		//check lai
        $land = 1;
		$uid = $this->session->userdata('uid');
		/*
		* lay thong tin huan luyen quan doi tai manh dat va vi tri nay
		* ------------------------------------------------------------------------------
		*/
		
		$this->update_all_info_user($uid);
		$this->update_all_res_user($uid);
		$rInfo = $this->run_time_res($uid);
        
		$data['rfood'] = $rInfo[0];
		$data['rwood'] = $rInfo[1];
		$data['rmetal'] = $rInfo[2];
		$data['rpetroleum'] = $rInfo[3];
		
		$res = $this->home_model->ww_get_res_user_info($uid);
		$data['res'] = $res;
        $data['res']['food'] = $res['food'] > $res['maxstore'] ? $res['maxstore'] : $res['food'];
        $data['res']['wood'] = $res['wood'] > $res['maxstore'] ? $res['maxstore'] : $res['wood'];
        $data['res']['metal'] = $res['metal'] > $res['maxstore'] ? $res['maxstore'] : $res['metal'];
        $data['res']['petroleum'] = $res['petroleum'] > $res['maxstore'] ? $res['maxstore'] : $res['petroleum'];
		/*
		*	check time 
		*
		*/
		$arrComplete = array(); // array id complete
		$arrNotComplete = array();
		$downTime = array();
		$train = $this->home_model->ww_get_train_user_info($uid, 0);
		//
		foreach($train as $pstime)
		{
			$timestamp = $pstime['timestamp'] + $pstime['eachtime'];
			$timenow = time();
			if($timenow > $timestamp)
			{
				/* 
				* neu thoi gian hien tai lon hon thoi gian ket thuc nhiem vu => da ket thuc nhiem vu
				* insert len database da hoan thanh nhiem vu => lay array id cua nv de insert complete
				* kich hoat them don vi cho nguoi choi
				*/
				//->$this->home_model->ww_update_quantity_military($uid, $pstime['id']);
				$arrComplete[] = $pstime['id'];
				//die();
			}
			else
			{
				/*
				* neu nhiem vu chua ket thuc
				* lay nhung id chua hoan thanh va show list
				* thoi gian chay = thoi gian tong(timestamp + eachtime) - thoi gian hien tai
				* cong tong cac thoi gian chay lai
				*/
				$pstime['tComplete'] = $pstime['timestamp'] + $pstime['eachtime'];
				$pstime['nice_timeComplete'] =  $this->mydatetime->nicetime(gmdate('Y-m-d H:i:s', $pstime['tComplete']));
				if(!isset($arrNotComplete[0]))
				{
					$downTime = $pstime;
				}
				$pstime['eachtime'] = ($pstime['timestamp'] + $pstime['eachtime']) - time();
				$arrNotComplete[] = $pstime;
				
			}
		}
		$data['info'] = $arrNotComplete;//echo $downTime;die();
		if(!empty($downTime))
		{
			if($downTime['eachtime'] == $downTime['lquantity']*$downTime['fixtime'])
			{
				$data['retime'] = $downTime['timestamp'] + $downTime['quantity']*$downTime['fixtime'] + $downTime['fixtime'] - $timenow;
			}
			else if($downTime['eachtime'] > $downTime['lquantity']*$downTime['fixtime'])
			{
				$data['retime'] = $downTime['timestamp'] + $downTime['eachtime'] - $downTime['lquantity']*$downTime['fixtime'] + $downTime['quantity']*$downTime['fixtime'] + $downTime['fixtime'] - $timenow;
			}
			else
			{
				$data['retime'] = $downTime['fixtime'];
			}
		}
		/*
		* get time chay don vi dau tien
		*/
		$data['chk_rtime'] = false;
		if(!empty($downTime))
		{
			$data['chk_rtime'] = true;
		}
		/*
		* lay thong tin so luong cac don vi hien tai dang co o vi tri nay
		* tam thoi dat $land = 1
		*------------------------------------------------------------------------------
		*/
		
		//-------------- chu y cho nay
		$land = 0;//??????
		//---------------
		$data['unit'] = $this->home_model->ww_get_units_user_info($uid, $land);
		
		// header
		
		// content
		$this->load->view('home/home_view', $data);
		
		// foter
	}
	
	public function add_military()
	{
	   if(!$this->session->userdata('username'))
       {
            redirect(site_url('login'));
            die();
       }
		// check session user
		$arr_unit = array(
			'u2', // linh bo binh
			'u3', // linh ban tia
			'u4', // linh chong tang
			'u5', // xe chien dau bo binh
			'u6', // xe thiet giap cho quan
			'u7', // xe thiet giap trinh sat
			'u8', // xe thiet giap chong min
			'u9', // xe thiet giap boc thep
			'u10', // xe tang hanh nhe
			'u11', // xe tang chien dau chu luc
			'u12', // sung coi
			'u13', // son phao
			'u14', // luu phao
			'u15', // phao phan luc
			'u16', // phao tu hanh
			'u17', // phao cao xa
			'u18', // phao phong khong tu hanh
			'u19', //
			'u20', //
			'u21', //
			'u22', //
			'u23', //
			'u24', //
			'u25', //
			'u26', //
			'u27', //
			'u28', //
			'u29', //
			'u30', //
			'u31', //
			'u32', //
			'u33', //
			'u34', //
			'u35', //
			'u36', //
			'u37', //
			'u38', //
			'u39', //
			'u40', //
			'u41', //
			'u42', //
			'u43', //
			'u44', //
			'u45', //
			'u46', //
			'u47', //
			'u48', //
			'u49', //
			'u50', //
			'u51', //
			'u52', //
			'u53', //
			'u54', //
			'u55', //
			'u56', //
			'u57', //
			'u58', //
			'u59', //
			'u60', //
			'u61', //
			'u62', //
			'u63', //
			'u64', //
			'u65', //
		);
		
		$unit = $this->input->post('obj');
		$val = (int)$this->input->post('val');
		
		// check ton tai trong unit
		$chk_arrUnit = !in_array($unit, $arr_unit) ? true : false;
		// check tai nguyen co du de mua khong
		
		// check don vi da dc unlock chua
		
		// tru tai nguyen
		
		// update them don vi
		
		//check lai
		$uid = $this->session->userdata('uid');
		$land = 1;
		$pos = 0;
		$unit = substr($unit,1);
		$quantity = $lquantity = $val;
		$timestamp = time();
		$fixtime = 5;
		$status = 0;
		//
		$eachtime = $fixtime*$val;
		//trainning units
		$this->home_model->ww_update_training_military($uid, $land, $pos, $unit, $lquantity, $timestamp, $eachtime, $fixtime, $status);
		
		//update units
		//$this->home_model->ww_update_quantity_military($uid, $land, $pos, $unit, $val);
	}
	public function update_all_info_user($uid)
	{
	   if(!$this->session->userdata('username'))
       {
            redirect(site_url('login'));
            die();
       }
		/*
		* update_all_info_user
		*/
		$info_train = $this->home_model->ww_get_train_user_info($uid, 0);
		
		$arrUnit = array();
		$arrVal = array();
		$strSuccess = '';
		$chkExistsCompleteTrain = false;
		foreach($info_train as $info)
		{
			// dat thoi gian tre khoang 5s.
			$timestamp = $info['timestamp'] + $info['eachtime'] + 5;
			$timenow = time();
			
			if($timenow > $timestamp)
			{
				/*
				* check id nhung traning da dc hoan thanh.
				*/
				$arrIDSuccess[] = $info['id'];
				if(!in_array('u'.$info['unit'], $arrUnit))
				{
					$arrUnit[] = 'u'.$info['unit'];
					$arrVal[] = $info['lquantity'] - $info['quantity'];
				}
				else
				{
					$valKey = array_search('u'.$info['unit'], $arrUnit);
					$arrVal[$valKey] = $arrVal[$valKey] + $info['lquantity'] - $info['quantity'];
				}
				$chkExistsCompleteTrain = true;
			}
			else
			{
				/*
				* check id nhung traning chua hoan thanh, chay thoi gian.
				*/
				
				// thoi gian hoan thanh tren db.
				$chkTime_v1 = $info['timestamp'] + $info['eachtime'];
				// thoi gian hien tai + thoi gian chuan hoan thanh khong tinh thoi gian traning truoc.
				$chkTime_v2 = $timenow + $info['fixtime']*$info['lquantity'];
				
				// thoi gian hoan thanh - thoi gian can ban de lay thoi gian du.
				$chkTime_v3 = $info['eachtime'] - $info['fixtime']*$info['lquantity'];
				
				
				// neu thoi gian 2 > thoi gian 1-> thoi gian hien tai da chuan bi hoan thanh
				//, kiem tra traning do'.
				if($chkTime_v2 > $chkTime_v1)
				{
					// gia tri $quantity la so nguyen to cua so luong da hoan thanh.
					$decimal = ($timenow - ($info['timestamp']+$chkTime_v3))/$info['fixtime'];
					$quantity = floor($decimal);
					$quantity = $quantity > $info['lquantity'] ? $info['lquantity'] : $quantity;
					
					if($decimal >= 1 && $quantity>=1 && $quantity > $info['quantity'])
					{
						$quantity = $quantity - $info['quantity'];
                        $this->home_model->ww_update_quantity_for_time($info['id'], $uid, $quantity);
					}
				}
			}
			// end if
		}
		/*
		* thao tac hoan thanh len db.
		*/
        
		if($chkExistsCompleteTrain)
		{
			$arrStr = array();
			$lstid = join(",", $arrIDSuccess);
			$i = 0;
			foreach($arrUnit as $typeUnit)
			{
				$strSuccess .= $typeUnit.'='.$typeUnit.'+'.$arrVal[$i].',';
				$i++;
			}
			$strSuccess = substr($strSuccess, 0, -1);
			$this->home_model->ww_update_quantity_military($uid, $strSuccess, $lstid);
		}
		// end for
	}
	function run_time_res($uid)
	{
		/*
		chia cho 1 phut
		*/
		$food = 60000/($this->_food/60);
		$wood = 60000/($this->_wood/60);
		$metal = 60000/($this->_metal/60);
		$petroleum = 60000/($this->_petroleum/60);
		
		$result = array($food, $wood, $metal, $petroleum);
		return $result;
	}
	function update_all_res_user($uid, $land)
	{
		$data = array();
		$food = $this->_food;
		$wood = $this->_wood;
		$metal = $this->_metal;
		$petroleum = $this->_petroleum;
		$time = time();
		$res = $this->home_model->ww_get_res_user_info($uid);
		
		$lastupdate = $res['lastupdate'];
		
		$valFloat = (((($time - $lastupdate)/60)/60)/2);
		$food = floor($valFloat*$food);
		$wood = floor($valFloat*$wood);
		$metal = floor($valFloat*$metal);
		$petroleum = floor($valFloat*$petroleum);
		if($food >= 1 || $wood >= 1 || $metal >= 1 || $petroleum >= 1)
		{
			$update_res_by_hour = $this->home_model->ww_update_res_by_hour($uid, $land, $food, $wood, $metal, $petroleum, $time);
		}
	}
	function formatMilitary($number, $type)
	{
		if($type == 1)
		{
			/*
			* luc quan
			*/
			// tieu doi 
			if($number < 36) // neu so luong nho hon trung doi
			{
				/*
				* tieu doi 12 nguoi
				*/
				$nSquad = (int)($number/12);
				if($nSquad <= 2)
				{
					$name = $squad = $nSquad.' tiểu đội';
				}
			}
			else if($number < 100)
			{
				/*
				* trung doi 36 nguoi
				*/
				$nPlatoon = (int)($number/36);
				if($nPlatoon <= 2)
				{
					$name = $platoon = $nPlatoon.' trung đội';
				}
			}
			else if($number < 324)
			{
				/*
				* dai doi 100 nguoi
				*/
				$nTroop = (int)($number/100);
				if($nTroop <= 2)
				{
					$name = $troop = $nTroop.' đại đội';
				}
			}
			else if($number < 3000)
			{
				/*
				* tieu doan 12 nguoi
				* 3 dai doi bo binh
				* 1 trung doi hoa luc - 3 khau phao va 24 nguoi
				*/
				$nSquadron = (int)($number/324);
				if($nSquadron <= 2)
				{
					$name = $squadron = $nSquadron.' tiểu đoàn';
				}
			}
			else if($number < 3500)
			{
				/*
				* tieu doan 12 nguoi
				* 3 dai doi bo binh
				* 1 trung doi hoa luc
				*/
				$nRegiment = (int)($number/3000);
				if($nRegiment == 1)
				{
					$name = $regiment = $nRegiment.' trung đoàn';
				}
			}
			else if($number < 9000)
			{
				/*
				* tieu doan 12 nguoi
				* 3 dai doi bo binh
				* 1 trung doi hoa luc
				*/
				$nBrigade = (int)($number/3000);
				if($nBrigade <= 2)
				{
					$name = $brigade = $nBrigade.' lữ đoàn';
				}
			}
			else if($number < 50000)
			{
				/*
				* tieu doan 12 nguoi
				* 3 dai doi bo binh
				* 1 trung doi hoa luc
				*/
				$nDivision = (int)($number/9000);
				if($nDivision <= 4)
				{
					$name = $division = $nDivision.' sư đoàn';
				}
			}
			else if($number < 50000)
			{
				/*
				* tieu doan 12 nguoi
				* 3 dai doi bo binh
				* 1 trung doi hoa luc
				*/
				$nCorps = (int)($number/9000);
				$name = $corps = $nCorps.' quân đoàn';
			}
		}
		return $name;
	}
	
	function training()
	{
		// neu session ko co thi thoat
		/*
		*	$uid -> id nguoi choi;
		*	$troop_code -> code cua binh linh
		*	$quantity -> so luong
		*	$timestamps -> thoi gian mua
		*	$eachtime-> thoi gian ra qua
		*/
		$info = $this->home_model->add_training_military($uid, $troop_code, $quantity, $timestamps, $eachtime);
	}
}